<template>
	<div class="machine-state-monitor-container">
		<el-row class="header-box">
			<el-col :span="8" class="header-box-left">
				<kan-ban-dropdown
					v-model="searchParams.workshopId"
					:option-list="workshopList"
					@change="onSelectDropdown"
				></kan-ban-dropdown>
			</el-col>
			<el-col :span="8" class="header-box-title">设备状态监控</el-col>
			<el-col :span="8" class="header-box-right">
				<span class="current-time">{{ currentTime }}</span>
				<jk-full-screen-button class-name="machine-state-monitor-container"></jk-full-screen-button>
				<el-button :loading="refreshBtnLoading" size="mini" type="primary" icon="el-icon-refresh" style="margin-left: 4px;" @click="onRefreshBtn"></el-button>
			</el-col>
		</el-row>
		<article class="article-box">
			<div class="article-top">
				<div class="article-top-left chart-item">
					<div class="chart-item-inner">
						<div class="chart-title">
							<div
								v-for="(item, index) in machineStateList"
								:key="index"
								class="flex-start-center margin-right-10"
							>
								<div style="width: 6px; height: 6px;margin-right: 4px;" :style="{background: item.color}"></div>
								<span>{{ item.name }}</span>
							</div>
						</div>
						<div class="chart-container">
							<grid-layout
								ref="gridlayout"
								:layout.sync="ruleForm.machineLayoutList"
								:col-num="ruleForm.colNum"
								:row-height="ruleForm.rowHeight"
								:is-draggable="false"
								:margin="[0, 0]"
								:auto-size="false"
								:is-resizable="false"
								:responsive="false"
								:vertical-compact="false"
								:prevent-collision="true"
								:use-css-transforms="true"
							>
								<grid-item
									v-for="(item) in ruleForm.machineLayoutList"
									:key="item.id"
									:x="item.x"
									:y="item.y"
									:w="item.w"
									:h="item.h"
									:i="item.i"
									:style="setGridStyle(item)"
									class="grid-item anim-machine"
									@click.native="onSelectMachineItem(item)"
								>
									<div :ref="`bt`+item.id" style="height: 100%;width: 100%;" class="flex-center">
										<span>{{ item.name }}</span>
									</div>
								</grid-item>
							</grid-layout>
						</div>
					</div>
				</div>
				<div class="article-top-right chart-item" style="padding-left: 12px;">
					<div class="chart-item-inner">
						<div class="chart-title">设备状态分析</div>
						<div class="chart-container">
							<div style="height: 50%;">
								<machine-state-chart :chart-data="stateList"></machine-state-chart>
							</div>
							<div style="height: 50%;">
								<div class="chart-title">异常告警信息</div>
								<el-row
									v-for="(item, index) in errorMsgList"
									:key="index"
									class="alert-msg-item"
									:style="{ color: item.status ? '#19be6b' : '#ff9900' }"
								>
									<el-col :span="10" class="alert-msg-status text-ellipsis">
										<div class="alert-msg-status-icon el-icon-warning" :style="{ color: item.status ? '#19be6b' : '#ff9900' }"></div>
										<span>{{ item.time }}</span>
									</el-col>
									<el-col :span="7" class="alert-msg-txt text-ellipsis">{{ item.deviceRecordName }}</el-col>
									<el-col :span="7" class="alert-msg-txt text-ellipsis">无数据上传!</el-col>
								</el-row>
							</div>
						</div>
					</div>
				</div>
			</div>
		</article>
		<detailDialog
			ref="machineParamsDialog"
			:machine-data="machineData"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detailDialog>
	</div>
</template>
<script>
    import machineStateChart from './components/machine-state-chart';
    import kanBanDropdown from '../kanBan/componenst/kan-ban-dropdown';
    import VueGridLayout from 'vue-grid-layout';
    import {
        iotDeviceAlarmRecordPage,
        machineManagerMachineGetRunState,
        workshopLayoutGetByWorkshopId
    } from '../../../api/intelligence';
    import colorMixin from '../orderTracking/colors-mixin';
    import detailDialog from './detail-dialog';
    import { formatTime } from '../../../utils/jk/jk-tool';

    export default {
        mixins: [colorMixin],
        components: {
            detailDialog,
            kanBanDropdown,
            machineStateChart,
            GridLayout: VueGridLayout.GridLayout,
            GridItem: VueGridLayout.GridItem
        },
        data() {
            return {
                currentTime: '',
                machineData: {},
                detailDialogState: false,
                timer3: {},
                timer2: {},
                timer: {},
                refreshBtnLoading: false,
                ruleForm: {
                    machineLayoutList: [],
                    colNum: 48,
                    rowHeight: 4,
                    workshopId: null,
                    workshopCode: '',
                    workshopName: ''
                },
                layoutList: [],
                workshopList: [],
                searchParams: {
                    workshopId: null,
                    customerName: '',
                    selectOpen: true
                },
                machineRunStateList: [],
                errorMsgList: []
            };
        },
        methods: {
            onSelectMachineItem(e) {
                this.machineData = e;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                this.detailDialogState = e;
            },
            onRefreshBtn() {
                this.getDependentData();
            },
            setGridStyle(item) {
                const stateItem = this.machineStateList.find(x => x.id === item.state) || {};
                return {
                    cursor: 'pointer',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    fontSize: '12px',
                    color: '#fff',
                    background: stateItem.color || '#808695'
                };
            },
            onSelectDropdown(e) {
                this.$set(this.searchParams, 'workshopId', e);
                this.$set(this.ruleForm, 'machineLayoutList', []);
                this.getWorkshopLayoutList();
            },
            getWorkshopLayoutList() {
                return workshopLayoutGetByWorkshopId({ id: this.searchParams.workshopId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {
                            machineLayoutList: [],
                            colNum: 48,
                            rowHeight: 4,
                            workshopId: null,
                            workshopCode: '',
                            workshopName: ''
                        };
                        this.ruleForm = resData;
                        this.getMachineRunStateRequest();
                    } else {
                        this.refreshBtnLoading = false;
                    }
                });
            },
            setMachineState() {
                this.ruleForm.machineLayoutList.forEach(layoutMachineItem => {
                    this.machineRunStateList.forEach(runMachineItem => {
                        if (layoutMachineItem.machineCode === runMachineItem.machineCode) {
                            this.$set(layoutMachineItem, 'state', runMachineItem.state);
                        }
                    });
                });
            },
            getMachineRunStateRequest() {
                if (!this.searchParams.workshopId) return false;
                return machineManagerMachineGetRunState({ workshopIds: [this.searchParams.workshopId] }).then(res => {
                    this.refreshBtnLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        this.machineRunStateList = [];
                        if (res.data.res) {
                            res.data.res.forEach(x => {
                                x.machineRunStateList.forEach(k => {
                                    this.machineRunStateList.push(k);
                                });
                            });
                        }
                        for (const keyName in this.stateList) {
                            this.stateList[keyName].count = this.machineRunStateList.filter(x => x.state === Number(keyName)).length;
                        }
                        // 初始化
                        this.machineStateList.forEach(x => {
                            x.count = 0;
                        });
                        resData.forEach(x => {
                            x.machineRunStateList.forEach(k => {
                                this.machineStateList.forEach(x => {
                                    if (x.id === k.state) {
                                        x.count += 1;
                                    }
                                });
                            });
                        });
                        this.setMachineState();
                    }
                });
            },
            getAlertListRequest() {
                return iotDeviceAlarmRecordPage({
                    ...this.searchParams,
                    pageNo: 1,
                    pageSize: 20
                }).then(res => {
                    if (res.data.status === 200) {
                        this.errorMsgList = res.data.res.map(x => {
                            x.time = x.createTime.substring(5, x.createTime.length);
                            return x;
                        });
                    }
                });
            },
            async getDependentData() {
                this.refreshBtnLoading = true;
                if (this.searchParams.workshopId) await this.getWorkshopLayoutList();
                if (this.searchParams.workshopId) await this.getAlertListRequest();
                this.refreshBtnLoading = false;
            },
            getCurrentTime() {
                this.currentTime = formatTime(Date.now());
                this.timer3 = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            run() {
                this.timer = setInterval(() => {
                    this.getMachineRunStateRequest();
                }, 5 * 1000);
            },
            run2() {
                this.timer2 = setInterval(() => {
                    this.getAlertListRequest();
                }, 60 * 1000);
            }

        },
        mounted() {
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.workshopList = _this.$store.state.user.userWorkshop.workshopList;
                _this.$set(_this.searchParams, 'workshopId', _this.$store.state.user.userWorkshop.defaultWorkshopId);
                _this.getDependentData();
                _this.run();
                _this.run2();
                _this.getCurrentTime();
                // 针对keepAlive等于true时,如果详情弹窗是打开状态，开启它的定时器
                if (_this.$refs.machineParamsDialog.showDialog) {
                    _this.$refs.machineParamsDialog.run();
                }
            });
        },
        beforeRouteLeave(to, from, next) {
            // 清除详情弹窗定时器
            this.$refs.machineParamsDialog.clearTimer();
            clearInterval(this.timer);
            clearInterval(this.timer2);
            clearInterval(this.timer3);
            next();
        }
    };
</script>
<style scoped lang="scss">
    $border_color: #515a6e;
    $header_height: 80px;
    .machine-state-monitor-container {
    width: 100%;
    height: 100vh;
    color: #fff;
    overflow: auto;
    background: #000E25;
    background-size: cover;
    .header-box {
        width: 100%;
        height: $header_height;
        background: url("../../../assets/images/largeCentralControlScreen/header_bg.png") no-repeat center;
        background-size: 100% 100%;
        padding: 0 16px;
        .header-box-title {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            font-size: 32px;
            font-weight: 700;
            text-shadow: 0 0 20px #fff;
        }
        .header-box-left {
            height: 100%;
            display: flex;
            align-items: flex-end;
        }
        .header-box-right {
            height: 100%;
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;
            .current-time {
                font-size: 20px;
                margin-right: 10px;
            }
        }
    }
    .article-box {
        width: 100%;
        height: calc(100% - #{$header_height});
        padding: 12px 16px;
        box-sizing: border-box;
        .chart-item {
            width: 100%;
            height: 100%;
            padding: 6px 0;
            box-sizing: border-box;
            .chart-item-inner {
                width: 100%;
                height: 100%;
                box-shadow: 0 0 4px 2px #2d8cf0;
                border-radius: 10px;
                .chart-container {
                    width: 100%;
                    height: calc(100% - 52px);
                    box-sizing: border-box;
                    padding: 12px;
                    overflow: auto;
                    .workshop-item {
                        width: 33.333%;
                        height: 100%;
                        background: #092D65;
                        border-radius: 10px;
                        padding: 16px;
                        display: flex;
                        flex-direction: column;
                        box-sizing: border-box;
                        margin: 0 6px;
                        .workshop-item-title {
                            width: 50px;
                            font-size: 16px;
                            border-bottom: solid 2px #dcdee2;
                            margin-bottom: 10px;
                            padding-bottom: 2px;
                        }
                        .tem-hum-box {
                            display: flex;
                            align-items: center;
                            margin: 10px 0;
                            .tem-hum-icon {
                                width: 30px;
                                height: 30px;
                                border-radius: 50%;
                                border: solid 1px #fff;
                                display: flex;
                                justify-content: center;
                                align-items: center;
                                font-size: 20px;
                                margin-right: 10px;
                            }
                            .tem-hum-val {
                                font-size: 22px;
                                margin-right: 10px;
                            }
                        }
                    }
                    .alert-msg-item {
                        width: 100%;
                        margin: 6px 0;
                        display: flex;
                        align-items: center;
                        box-sizing: border-box;
                        .alert-msg-status {
                            display: flex;
                            align-items: center;
                            font-size: 13px!important;
                            .alert-msg-status-icon {
                                //width: 10px;
                                //height: 10px;
                                //border-radius: 50%;
                                margin-right: 4px;
                                flex-shrink: 0;
                                font-size: 16px;
                            }
                        }
                        .alert-msg-txt {
                            font-size: 13px!important;
                            padding-left: 10px;
                            box-sizing: border-box;
                        }
                    }
                }
                // 滚动条样式
                .chart-container::-webkit-scrollbar{
                    width: 6px;
                    height: 7px;
                }
                .chart-container::-webkit-scrollbar-thumb:hover{
                    width: 6px;
                    height: 7px;
                    cursor: pointer;
                    background-color: #114896;
                }
                .chart-container::-webkit-scrollbar-thumb{
                    border-radius: 1em;
                    background-color: #1A2F68;
                }
                .chart-container::-webkit-scrollbar-track{
                    border-radius: 1em;
                    background-color: rgba(50,50,50,.1);
                }
            }
        }
        .chart-title {
            width: 100%;
            height: 42px;
            font-size: 14px;
            background: url("./components/card-title.png") no-repeat center;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .article-top {
            width: 100%;
            height: 100%;
            display: flex;
            .article-top-left {
                width: 100%;
                height: 100%;
            }
            .article-top-right {
                width: 500px;
                float: right;
                height: 100%;
            }
        }
        .article-bottom {
            height: 0%;
        }
    }
}
    .anim-machine {
        animation: myAni 5s linear infinite;

    }
    @keyframes myAni {
        0% {
            //opacity: 1;
            //background: #2d8cf0;
        }
        50% {
            //background: #2d8cf0;
            //opacity: 0.5;
        }
        100% {
            //background: #2d8cf0;
            //opacity: 1;
        }
    }
</style>
